import '../public.dart';

/// 用户阅读历史和收藏记录
class UserRecordProvider with ChangeNotifier {
  UserRecordModel data;
  List<UserReadItemModel> userRead = [];
  List<UserCollectItemModel> userCollect = [];
  int collectNum = 0;
  int limitCollect = 0;
  int checkedCollectNum = 0;
  bool isCheckedAllCollect = false;

  // 设置用户记录，包括用户阅读历史和用户收藏记录
  Future setUserRecord() {
    return UserService.getUserRecord().then((res) {
      data = res;
      userRead = res?.userRead;
      userCollect = res?.userCollect;
      collectNum = res?.collectNum;
      limitCollect = res?.limitCollect;
      LogUtil.v(res);
      notifyListeners();
      return res;
    }).catchError((err) {
      LogUtil.e(err);
    });
  }

  // 删除用户阅读历史
  deleteUserRecord() {
    userRead = [];
    userCollect = [];
    data = null;
    notifyListeners();
  }

  // 删除用户阅读历史
  deleteUserRead() {
    userRead = [];
    notifyListeners();
  }

  // 删除用户收藏记录
  deleteUserCollect([List<int> list = const []]) {
    if (list.length > 0) {
      list.forEach((comicId) {
        userCollect.forEach((item) {
          if (comicId == item.comicId) {
            userCollect.remove(item);
            return;
          }
        });
      });
    } else {
      userCollect = [];
    }
    notifyListeners();
  }

  // 设置checked列表，0个为取消所有全选操作，1个为单个选择操作，大于1为全选操作（注需要传入所有数据列表）；
  checkedUserCollect(List<UserCollectItemModel> list) {
    int len = list.length ?? 0;
    list.forEach((item) {
      if (list.length == 1) {
        item.isChecked = !item.isChecked;
      } else {
        item.isChecked = !isCheckedAllCollect;
      }
    });
    // 获得选择数量
    int checkedNum = 0;
    userCollect.forEach((item) {
      if (len > 0) {
        if (item.isChecked) {
          checkedNum++;
        }
      } else {
        item.isChecked = false;
      }
    });
    checkedCollectNum = checkedNum;
    isCheckedAllCollect = checkedNum == userCollect.length;
    notifyListeners();
  }
}
